package com.study.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.core.lang.UUID;
import com.study.VO.request.LoginVO;
import com.study.VO.response.CaptchaDTO;
import com.study.result.ResultUtil;
import com.study.utils.RedisUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;

/**
 * 测试登录
 *
 * @author xupt
 */
@RestController
public class LoginController {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    public Object captcha() {
        //生成gif验证码，长200，宽100，4位数
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(200, 100, 4);
        //创建数组缓冲区
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //写入验证码
        gifCaptcha.write(outputStream);
        //BASE64加密算法
        BASE64Encoder encoder = new BASE64Encoder();
        //base64图片头
        String imgHeader = "data:image/jpeg;base64,";
        //完整的base64
        String base64Img = imgHeader + encoder.encode(outputStream.toByteArray()).replaceAll("\r\n", "");
        //存入redis的key
        String redisKey = UUID.randomUUID().toString();
        // 设置redis保存的验证码信息过期时间
        redisUtil.set(redisKey, gifCaptcha.getCode(), 120);
        return ResultUtil.success(new CaptchaDTO(redisKey, base64Img));
    }

    /**
     * 检测验证码
     */
    @PostMapping("check")
    public Object check(@RequestBody LoginVO loginVO) {
        //获取redis中存储的验证码值
        String redisCaptcha = (String) redisUtil.get(loginVO.getCaptchaKey());
        //忽略大小进行比较
        if (redisCaptcha!=null&&redisCaptcha.equalsIgnoreCase(loginVO.getCaptchaCode())) {
            return ResultUtil.success("验证通过");
        } else {
            return ResultUtil.success("验证失败");
        }
    }

}
